import GoodsSelect, { GoodsSelectRef } from "@/components/dataEntry/GoodsSelect";
import { GoodsRecord } from "@/views/goods/GoodsList/GoodsListType";
import { Form, FormInstance } from "antd";
import { cloneDeep } from "lodash";
import { useContext, useEffect, useRef } from "react";
import { ConfigurePageContext } from "../../ConfigurePage";
import { GoodsItem } from "../../ConfigurePageType";
const GoodsEditor = () => {
	const { selectedIndex, content, setContent } = useContext(ConfigurePageContext);
	const formRef = useRef<FormInstance>(null);
	const goodsSelectRef = useRef<GoodsSelectRef>(null);
	useEffect(() => {
		if (selectedIndex !== null) {
			const list = content[selectedIndex].list as GoodsItem[];
			const ids = list.map(item => item._id);
			formRef.current?.setFieldValue("goods", ids);
			goodsSelectRef.current?.insertGoodsByIds(ids);
		}
	}, []);
	return (
		<>
			<Form ref={formRef}>
				<Form.Item label="请选择商品" name="goods">
					<GoodsSelect
						ref={goodsSelectRef}
						mode="multiple"
						onGoodsChange={goods => {
							if (selectedIndex === null) return;
							const copiedContent = cloneDeep(content);
							// eslint-disable-next-line @typescript-eslint/no-unused-vars
							copiedContent[selectedIndex].list = (goods as GoodsRecord[]).map(({ status, createdTime, updatedTime, ...remainingGoodsItem }) => ({
								...remainingGoodsItem,
								status: status === 1,
							}));
							setContent(copiedContent);
						}}
					/>
				</Form.Item>
			</Form>
		</>
	);
};

export default GoodsEditor;
